package mvc.core;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

/**
 * Http请求结果封装
 * 
 * @author liuzy
 * @version 2015年5月18日
 */
public class Response {
	private int status = 200;
	private String contentType = "text/plain;charset=utf-8";
	private String characterEncoding = "utf-8";
	private Map<String, String> header = new HashMap<String, String>();
	private String dateHeader;
	private String intHeader;
	private Object content;

	public Response() {
	}

	public Response(Object content) {
		this.content = content;
	}

	public Response(Object content, String contentType) {
		this.content = content;

		this.contentType = contentType;
	}

	/**
	 * 发送至客户端
	 * 
	 * @param response
	 * @throws IOException
	 */
	public void send(HttpServletResponse response) throws IOException {
		OutputStream os = response.getOutputStream();
		if (content instanceof File) {
			File file = (File) content;
			byte[] fileBytes = file.getFileBytes();
			this.setContentType("application/octet-stream");
			this.addHeader("Content-disposition", "attachment;filename=" + file.getFileName());
			os.write(fileBytes);
		} else {
			os.write(JSON.toJSONString(content).getBytes());
		}
		response.setStatus(status);
		response.setContentType(contentType);
		response.setCharacterEncoding(characterEncoding);
		response.setContentType(contentType);
		for (String key : header.keySet()) {
			response.addHeader(key, header.get(key));
		}
		os.flush();
		os.close();
	}

	/*
	 * 重写便于日志调试
	 */
	@Override
	public String toString() {
		return JSON.toJSONString(this);
	}

	public int getStatus() {
		return status;
	}

	public void setStatus(int status) {
		this.status = status;
	}

	public String getContentType() {
		return contentType;
	}

	public void setContentType(String contentType) {
		this.contentType = contentType;
	}

	public String getCharacterEncoding() {
		return characterEncoding;
	}

	public void setCharacterEncoding(String characterEncoding) {
		this.characterEncoding = characterEncoding;
	}

	public String getHeader(String key) {
		return header.get(key);
	}

	public void addHeader(String key, String value) {
		this.header.put(key, value);
	}

	public String getDateHeader() {
		return dateHeader;
	}

	public void setDateHeader(String dateHeader) {
		this.dateHeader = dateHeader;
	}

	public String getIntHeader() {
		return intHeader;
	}

	public void setIntHeader(String intHeader) {
		this.intHeader = intHeader;
	}

	public Object getContent() {
		return content;
	}

	public void setContent(Object data) {
		this.content = data;
	}
}
